package com.edais.actions;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.RunningSignUpInfo;
import com.edais.service.RunningService;
import com.edais.service.SMSService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.IDCard;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import com.edais.util.llpay.LLPayThridPartyFunctionUtil;

@Controller
@RequestMapping("/running")

public class RunningAction implements Serializable {
	private static final Log logger = LogFactory.getLog(RunningAction.class);
	
	@Autowired
	private RunningService runningService;
	
	@Autowired
	private SMSService sMSService;
	
	
	/**
	 * 更新报名表
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value = "/updateRunningSignUpInfo")
	public void updateRunningSignUpInfo(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String mobile = paramsMap.get("mobile");
		String payOrderId = paramsMap.get("payOrderId");
		String payAmount = paramsMap.get("payAmount");
		String payBankNo = paramsMap.get("payBankNo");
		
		if (StringUtils.isBlank(mobile)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE,
					"", "手机号不能为空");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		if (StringUtils.isBlank(payOrderId)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.CHECK_CODE,
					"", "订单号不能为空");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	
		RunningSignUpInfo runningSignUpInfo = new RunningSignUpInfo();
		runningSignUpInfo.setMobile(mobile);
		runningSignUpInfo.setPayOrderId(payOrderId);
		runningSignUpInfo.setPayAmount(payAmount);
		runningSignUpInfo.setPayBankNo(payBankNo);
		runningService.updateRunningSignUpInfo(runningSignUpInfo);
		
		String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.SUCCESS_CODE,
				"", "");
		// 处理返回结果
		CommonUtil.responseJson(result, response);
		return;
	}
	
	/**
	 * 预报名
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/signUp")
	public void signUp(HttpServletRequest request,HttpServletResponse response) {
		logger.info("***************进入方法running/signUp*************************开始");
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String mobile = paramsMap.get("mobile");// 手机号
		String realName = paramsMap.get("realName");// 真实姓名
		String idCard = paramsMap.get("idCard");// 身份证号
		String materielSize = paramsMap.get("materielSize");// 身份证号
		
		try {
			Map<String,String> checkMap = signUpCheck(paramsMap);
			if (null == checkMap
					|| !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkMap.get("code"),
						"", checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			/** 主处理 **/
			// 实名认证验证
			Map<String, String> requestMap = new HashMap<String, String>();
			requestMap.put("idCard", idCard);
			requestMap.put("nameCard", realName);
			// 生成订单号
			String outOrderNo = createNoOrder();
			Map<String, String> authResult = new HashMap<String, String>();
			requestMap.put("outOrderNo", outOrderNo);
			authResult = LLPayThridPartyFunctionUtil.getAuth(requestMap);

			if (authResult == null
					|| "sysException".equals(authResult.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						"", "实名认证失败");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} else if ("BusinessException".equals(authResult.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						"", String.valueOf(authResult.get("resmsg_cn")));
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			// 实名认证成功后先存入一条数据
			try {
				String rescode = authResult.get("rescode");
				if ("00".equals(authResult.get("rescode"))) {
					String llpayAuthResult = authResult.get("result");
					if (llpayAuthResult.equals("1")) {
						Map<String, Object> infoMap = new HashMap<String, Object>();
						infoMap.put("mobile",mobile);
						List<RunningSignUpInfo> rsu = runningService.getEnrollInfo(infoMap);
						RunningSignUpInfo runningSignUpInfo = new RunningSignUpInfo();
						// 性别
						String sex = IDCard.getSex(idCard);
						
						String llpayOrderNo = authResult.get("orderNo");
						if(rsu == null || rsu.size() == 0){
							runningSignUpInfo.setMobile(mobile);
							runningSignUpInfo.setRealName(realName);
							runningSignUpInfo.setGender(sex);
							runningSignUpInfo.setIdCard(idCard);
							runningSignUpInfo.setIdcardValidate("Y");
							runningSignUpInfo.setLlpayOrderNo(llpayOrderNo);
							runningSignUpInfo.setLlpayOutorderNo(outOrderNo);
							runningSignUpInfo.setIsPay("N");
							runningSignUpInfo.setStatus("0");
							runningSignUpInfo.setMaterielSize(materielSize);
							runningService.addRunningSignUpInfo(runningSignUpInfo);
						}else{
							runningSignUpInfo = rsu.get(0);
							runningSignUpInfo.setMobile(mobile);
							runningSignUpInfo.setRealName(realName);
							runningSignUpInfo.setGender(sex);
							runningSignUpInfo.setIdCard(idCard);
							runningSignUpInfo.setIdcardValidate("Y");
							runningSignUpInfo.setSignUpTime(new Date());
							runningSignUpInfo.setLlpayOrderNo(llpayOrderNo);
							runningSignUpInfo.setLlpayOutorderNo(outOrderNo);
							runningSignUpInfo.setIsPay("N");
							runningSignUpInfo.setStatus("0");
							runningSignUpInfo.setMaterielSize(materielSize);
							runningService.updateRunningSignUpInfo(runningSignUpInfo);
						}
					} else {
						String result = CommonUtil.setResultStringCn(
								new HashMap<String, Object>(), Consts.CHECK_CODE,
								"", "身份证号码或姓名输入有误，请确认后重新输入！");
						// 处理返回结果
						CommonUtil.responseJson(result, response);
						return;
					}
				} else {
					String result = CommonUtil.setResultStringCn(
							new HashMap<String, Object>(), Consts.CHECK_CODE,
							"", "身份证号码或姓名输入有误，请确认后重新输入！");
					// 处理返回结果
					CommonUtil.responseJson(result, response);
					return;
				}
			} catch (Exception e) {
				logger.info("========" + CommonUtil.printStackTraceToString(e)); 
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE,
						"", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}

			//查询数据 验证是否可支付
			Map<String, Object> infoMap = new HashMap<String, Object>();
			infoMap.put("mobile",mobile);
			List<RunningSignUpInfo> rsu = runningService.getSignUpInInfo(infoMap);
			// 预报名成功
			if (rsu != null && rsu.size() > 0) {
				//ouyy 预报名成功，发送提示短信
				try {
					sMSService.getSMSKz(mobile,"sms07002");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("getSMSKz" + CommonUtil.printStackTraceToString(e)); 
				}
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.SUCCESS_CODE,
						"", "");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			} else {
				RunningSignUpInfo runningSignUpInfo = new RunningSignUpInfo();
				runningSignUpInfo.setMobile(mobile);
				runningSignUpInfo.setDelFlg("1");
				runningService.updateRunningSignUpInfo(runningSignUpInfo);
				
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE,
						"", "对不起,没有名额了");
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
		} catch (Exception e) {
			logger.error("异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
				Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}

	/**
	 * 随机生成订单
	 * 
	 * @return
	 */
	public String createNoOrder() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String currTime = outFormat.format(now);

		String strReq = currTime;
		Random random = new Random();
		String result = "";
		for (int i = 0; i < 8; i++) {
			result += random.nextInt(10);
		}

		String requestNo = "LBAuth" + strReq + result;
		return requestNo;
	}
	
	/**
	 * 预报名数据检查
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> signUpCheck(Map<String, String> paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		String mobile = paramsMap.get("mobile");// 手机号
		String realName = paramsMap.get("realName");// 真实姓名
		String idCard = paramsMap.get("idCard");// 身份证号
		String materielSize = paramsMap.get("materielSize");// 物料尺码
		if (StringUtils.isBlank(mobile)) {
			logger.error("预报名数据检查： 手机号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "手机号不能为空");
			return resMap;
		}
		
		if(StringUtils.isBlank(realName)){
			logger.error("预报名数据检查： 姓名为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "姓名不能为空");
			return resMap;
		}

		if(StringUtils.isBlank(idCard)){
			logger.error("预报名数据检查： 身份证号为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "身份证号不能为空");
			return resMap;
		}

		if(StringUtils.isBlank(materielSize)){
			logger.error("预报名数据检查： 物料尺码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "物料尺码不能为空");
			return resMap;
		}
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	
	/**
	 * 查询剩余名额
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getSurplusPeople")
	public void getSurplusPeople(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			logger.info("running/getSurplusPeople*************************开始");
			// 解密请求参数
			Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
			//查询剩余名额
			String count = runningService.getSurplusPeople();
			jsonMap.put("count", count);
			jsonMap.put("rescode", Consts.SUCCESS_CODE);
			jsonMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
			jsonMap.put("resmsg_cn", "");
			/** 处理返回结果 */
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			
		} catch (Exception e) {
			logger.error("running/getSurplusPeople 异常:" + e.getMessage());
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.GETSURPLUSPEOPLE_ERROR);
			/** 处理返回结果 */
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
	}
	
	/**
	 * 查询报名者信息(考虑是否过期)
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getEnrollInfo")
	public void getEnrollInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		logger.info("running/getEnrollInfo*************************开始");
		// 解密请求参数
		
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String mobile = paramsMap.get("mobile");//是否过期的标识
		String checkTimeFlg  = paramsMap.get("checkTimeFlg");
		if(null!=checkTimeFlg && !"".equalsIgnoreCase(checkTimeFlg) && !"null".equalsIgnoreCase(checkTimeFlg)){
			checkTimeFlg="1";
		}else{
			checkTimeFlg="";
		}
		String result ="";
		try {
			// 获取报名者信息
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("mobile", mobile);
			map.put("checkTimeFlg", checkTimeFlg);
			if("".equals(mobile) || null == mobile || "null".equalsIgnoreCase(mobile)){
				result = CommonUtil.setResultStringCn(jsonMap,Consts.CHECK_CODE,"手机号不能为空", Message.CnDescriptionExpression.GETENROLLINFO_NULL_ERROR);
				logger.info("=========[查询报名者信息]：手机号不能为空"+mobile);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			List<RunningSignUpInfo> rsu = runningService.getEnrollInfo(map);
			if(null != rsu && rsu.size() != 0){
				jsonMap.put("enrollInfo", rsu.get(0));
				result = CommonUtil.setResultStringCn(jsonMap,Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
				logger.info("=========获取的EnrollInfo信息："+result);
			}else{
				result = CommonUtil.setResultStringCn(jsonMap,Consts.CHECK_CODE,"未查到该手机报名信息", Message.CnDescriptionExpression.GETENROLLINFO_GET_ERROR);
				logger.info("=========查询不到该手机号的报名信息："+mobile+"====报名信息="+result);
			}
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("running/getEnrollInfo 异常:" + e.getMessage());
			jsonMap.put("rescode", Consts.ERROR_CODE);
			jsonMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			jsonMap.put("resmsg_cn", Message.CnDescriptionExpression.GETENROLLINFO_ERROR);
			/** 处理返回结果 */
			result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
	}
	/**
	 * 连连支付回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/runningLLpayNotify")
	public void runningLLpayNotify(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String bindingReqNum = paramsMap.get("bindingReqNum");// 用户id
		String noAgree = paramsMap.get("noAgree");
		String moneyOrder = paramsMap.get("moneyOrder");
		String oidPayBill = paramsMap.get("oidPayBill");
		String reqStr = paramsMap.get("reqStr");
		logger.info("====================JavaService进入连连支付成功回调接口=======================");
		if (StringUtils.isBlank(bindingReqNum)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					"running/runningLLpayNotify 传入请求号为空");

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("running/runningLLpayNotify 传入请求号为空");
			return;
		}
		if (StringUtils.isBlank(moneyOrder)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					"running/runningLLpayNotify 传入充值金额为空");

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("running/runningLLpayNotify 传入充值金额为空");
			return;
		}
		if (StringUtils.isBlank(oidPayBill)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					"running/runningLLpayNotify 传入连连支付订单号为空");

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("running/runningLLpayNotify 传入连连支付订单号为空");
			return;
		}
		
		try{
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("bindingReqNum", bindingReqNum);
			requestMap.put("noAgree", noAgree);
			requestMap.put("moneyOrder", moneyOrder);
			requestMap.put("oidPayBill", oidPayBill);
			requestMap.put("reqStr", reqStr);
			
			jsonMap = this.runningService.runningLLpayNotify(requestMap);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("running/runningLLpayNotify 异常:"
					+ e.getCause());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
	
	/**
	 * 更新支付失败订单状态
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/marathonUpdateFaildOrder")
	public void marathonUpdateFaildOrder(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String mobile = paramsMap.get("mobile");
		
		if (StringUtils.isBlank(mobile)) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					"running/marathonUpdateFaildOrder 传入手机号为空");

			// 处理返回结果
			CommonUtil.responseJson(result, response);
			logger.debug("running/marathonUpdateFaildOrder 传入手机号为空");
			return;
		}
		
		try{
			Map<String, Object> requestMap = new HashMap<String, Object>();
			requestMap.put("mobile", mobile);
			
			jsonMap = this.runningService.marathonUpdateFaildOrder(requestMap);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		}catch (Exception e) {
			logger.error("running/marathonUpdateFaildOrder 异常:"
					+ e.getCause());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001,
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
		
	}
	
}
